package hongcaosp.app.android.user.qrcode;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Handler;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.ViewGroup;

import com.google.zxing.Result;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;

import java.util.List;

import hongcaosp.app.android.R;
import hongcaosp.app.android.user.UserDetailActivity;
import me.dm7.barcodescanner.core.IViewFinder;
import me.dm7.barcodescanner.core.ViewFinderView;
import me.dm7.barcodescanner.zxing.ZXingScannerView;
import xlj.lib.android.base.component.BaseActivity;
import xlj.lib.android.base.toastcompat.ToastManager;
import xlj.lib.android.base.utils.JsonUtil;
import xlj.lib.android.base.utils.StatusBarUtil;

public class QRScanActivity extends BaseActivity implements ZXingScannerView.ResultHandler {

    private ZXingScannerView mScannerView;

    @Override
    protected void initData(Intent intent) {

    }

    @Override
    protected void initView() {
        StatusBarUtil.setStatusBarDarkTheme(this,false);
        ViewGroup root = findViewById(R.id.root);
        mScannerView = new ZXingScannerView(this) {
            @Override
            protected IViewFinder createViewFinderView(Context context) {
                return new CustomViewFinderView(context);
            }
        };

        root.addView(mScannerView);

        AndPermission.with(this).runtime().permission(Manifest.permission.CAMERA).onGranted(new Action<List<String>>() {
            @Override
            public void onAction(List<String> data) {
                mScannerView.setResultHandler(QRScanActivity.this);
                mScannerView.startCamera();
            }
        }).onDenied(new Action<List<String>>() {
            @Override
            public void onAction(List<String> data) {
                ToastManager.getInstance().showToast("相机权限获取失败，无法进行扫码");
                finish();
            }
        }).start();
    }

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_qrcode;
    }

    @Override
    public void onResume() {
        super.onResume();
        mScannerView.setResultHandler(this);
        mScannerView.startCamera();
    }

    @Override
    public void onPause() {
        super.onPause();
        mScannerView.stopCamera();
    }

    @Override
    public void handleResult(Result result) {
        String url = result.toString();
        if (TextUtils.isEmpty(url)) {
            ToastManager.getInstance().showToast("扫码失败");
        } else {
            try {
                QRUserBean qrUserBean = JsonUtil.parse(url,QRUserBean.class);
                if (qrUserBean != null && qrUserBean.getUserId() != null) {
                    UserDetailActivity.toDetail(this,qrUserBean.getUserId());
                    finish();
                }
            } catch (Exception e) {
                ToastManager.getInstance().showToast("不支持的二维码");
            }
        }
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                mScannerView.resumeCameraPreview(QRScanActivity.this);
            }
        }, 2000);
    }

    public static void toActivity(Context context) {
        if (context != null) {
            Intent intent = new Intent(context,QRScanActivity.class);
            context.startActivity(intent);
        }
    }

    private static class CustomViewFinderView extends ViewFinderView {
        public static final String TRADE_MARK_TEXT = "扫一扫添加好友";
        public static final int TRADE_MARK_TEXT_SIZE_SP = 20;
        public final Paint PAINT = new Paint();

        public CustomViewFinderView(Context context) {
            super(context);
            init();
        }

        public CustomViewFinderView(Context context, AttributeSet attrs) {
            super(context, attrs);
            init();
        }

        private void init() {
            PAINT.setColor(Color.WHITE);
            PAINT.setAntiAlias(true);

            float textPixelSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
                    TRADE_MARK_TEXT_SIZE_SP, getResources().getDisplayMetrics());
            PAINT.setTextSize(textPixelSize);
        }

        @Override
        public void onDraw(Canvas canvas) {
            super.onDraw(canvas);
            drawTradeMark(canvas);
        }

        private void drawTradeMark(Canvas canvas) {
            Rect framingRect = getFramingRect();
            float tradeMarkTop;
            float tradeMarkLeft;
            if (framingRect != null) {
                tradeMarkTop = framingRect.bottom + PAINT.getTextSize() + 10;
                tradeMarkLeft = framingRect.left;
            } else {
                tradeMarkTop = 10;
                tradeMarkLeft = canvas.getHeight() - PAINT.getTextSize() - 10;
            }
            canvas.drawText(TRADE_MARK_TEXT, tradeMarkLeft, tradeMarkTop, PAINT);
        }
    }
}
